package com.efounder.chat.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.ChineseCharacterUtils;
import com.efounder.mobilecomps.contacts.User;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

public class UserDBManager {
    private SQLiteDatabase db;
    private int loginUserId;
    private static final String TAG = "UserDBManager";

    public UserDBManager() {

        this.loginUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID, "0")).intValue();
        this.db = GetDBHelper.getInstance().getDb();
    }

    /**
     * 插入或更新单个联系人
     *
     * @param user
     * @return
     */
    public long insertOrReplace(User user) {
        ContentValues values = getUserContentValues(user);
        return this.db.insertWithOnConflict("User", null, values, SQLiteDatabase.CONFLICT_REPLACE);

    }

    /**
     * 插入或更新多个联系人
     *
     * @param users
     */
    public void insertOrReplace(List<User> users) {
        long currentTime = System.currentTimeMillis();

//        this.db.beginTransaction();
//        for (Iterator<User> localIterator = users.iterator(); localIterator
//                .hasNext(); ) {
//            User user = (User) localIterator.next();
//            insertOrReplace(user);
//        }
//        this.db.setTransactionSuccessful();
//        this.db.endTransaction();
        //sql优化2018.3.5
        String sql = "insert or replace into User(userid,name,nickname,sex,phone,mobilephone,avatar,email,sigNature,deptId,type,enable" +
                ",publicKey,walletAddress,RSAPublicKey,wechatQrUrl,zhifubaoQrUrl,stranger_chat,nickname_py_initial,nickname_py_quanpin,planet) " +
                " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        SQLiteStatement stat = db.compileStatement(sql);
        db.beginTransaction();
        for (User user : users) {
            //todo 特殊处理
//            User currentUser = queryById(user.getId());
//            if (currentUser != null) {
//                user.setPublicKey(currentUser.getPublicKey());
//                user.setWalletAddress(currentUser.getWalletAddress());
//                user.setRSAPublicKey(currentUser.getRSAPublicKey());
//            }


            stat.bindLong(1, user.getId());
            stat.bindString(2, user.getName() == null ? "" : user.getName());
            stat.bindString(3, user.getNickName() == null ? "" : user.getNickName());
            stat.bindString(4, user.getSex() == null ? "M" : user.getSex());
            stat.bindString(5, user.getPhone() == null ? "" : user.getPhone());
            stat.bindString(6, user.getMobilePhone() == null ? "" : user.getMobilePhone());
            stat.bindString(7, user.getAvatar() == null ? "" : user.getAvatar());
            stat.bindString(8, user.getEmail() == null ? "" : user.getEmail());
            stat.bindString(9, user.getSigNature() == null ? "" : user.getSigNature());
            stat.bindLong(10, user.getDeptId());
            stat.bindLong(11, user.getType());
            stat.bindLong(12, 1);
            stat.bindString(13, user.getPublicKey() == null ? "" : user.getPublicKey());
            stat.bindString(14, user.getWalletAddress() == null ? "" : user.getWalletAddress());
            stat.bindString(15, user.getRSAPublicKey() == null ? "" : user.getRSAPublicKey());
            stat.bindString(16, user.getWeixinQrUrl() == null ? "" : user.getWeixinQrUrl());
            stat.bindString(17, user.getZhifubaoQrUrl() == null ? "" : user.getZhifubaoQrUrl());
            stat.bindLong(18, user.isGroupBanSpeak() ? 1 : 0);
            stat.bindString(19, user.getNickName() == null ? "" : ChineseCharacterUtils.getJianPin(user.getNickName()));
            stat.bindString(20, user.getNickName() == null ? "" : ChineseCharacterUtils.getQuanPin(user.getNickName()));
            stat.bindString(21, user.getPlanet() == null ? "" : user.getPlanet());

            stat.executeInsert();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Log.i(TAG, System.currentTimeMillis() - currentTime + "ms 插入User表sql执行时间");

    }

    /**
     * 通过id查询联系人
     *
     * @param id
     * @return
     */
    public User queryById(int id) {
        //String sql = "select * from user where userId=" + id +" and enable =1 ;";
        String sql = "select * from User left join (select friends.userid as fuserid,friends.istop," +
                "friends.isbother,friends.remark from Friends where Friends.userId=" + id + " and friends.enable =1 " +
                " and friends.loginuserid=" + loginUserId + ") b" +
                " on User.userId = b.fuserId where User.userId =" + id;

        List<?> list = query(sql);
        return ((list.size() == 0) ? null : (User) list.get(0));

    }

//	/**
//	 * 查询所有联系人
//	 * @return
//	 */
//	public List<User> queryAllIsFriend() {
//		String sql = "select * from user where enable =1";
//		List<User> list = query(sql);
//		return list;
//
//	}

    /**
     * 查询所有联系人
     *
     * @return
     */
    public List<User> queryAll() {
        String sql = "select * from user where enable =1 where type =0 ";
        List<User> list = query(sql);
        return list;

    }

    /**
     * 查询所有关注的公众号
     *
     * @return
     */
    public List<User> queryAllOfficialNumber() {
        String sql = "select * from user where enable =1 where type =1 ";
        List<User> list = query(sql);
        return list;

    }

    /**
     * 更新联系人(单个)
     *
     * @param user
     * @return
     */
    public int update(User user) {
        ContentValues values = getUserContentValues(user);
        String whereClause = "userId=?";
        String[] whereArgs = {String.valueOf(user.getId())};
        return this.db.update("user", values, whereClause, whereArgs);
    }

    /**
     * 更新联系人(list)
     *
     * @param list
     * @return
     */
    public void update(List<User> list) {
        this.db.beginTransaction();
        for (Iterator<User> localIterator = list.iterator(); localIterator
                .hasNext(); ) {
            User user = (User) localIterator.next();
            update(user);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    /**
     * 删除联系人（单个）
     *
     * @param user
     * @return
     */
    public void delete(User user) {

        this.db.execSQL("update user set enable=0 where userId =" + user.getId() + ";");
    }

    /**
     * 删除联系人（单个）
     *
     * @return
     */
    public void delete(int userId) {

        this.db.execSQL("update user set enable=0 where userId =" + userId + ";");
    }


    /**
     * 删除联系人（多个）
     *
     * @param userList
     */
    public void delete(List<User> userList) {
        this.db.beginTransaction();
        for (Iterator<User> localIterator = userList.iterator(); localIterator
                .hasNext(); ) {
            User user = (User) localIterator.next();
            delete(user);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    public List<User> query(String sql) {
        return query(sql, null);
    }

    public List<User> query(String sql, String[] selectionArgs) {
        List<User> list = new ArrayList<User>();
        Cursor cursor = this.db.rawQuery(sql, selectionArgs);
        while (cursor.moveToNext()) {
            User user = new User();
            user.setId(cursor.getInt(cursor.getColumnIndex("userId")));

            user.setName(cursor.getString(cursor.getColumnIndex("name")));
            user.setNickName(cursor.getString(cursor.getColumnIndex("nickName")));

            String sex = cursor.getString(cursor.getColumnIndex("sex"));
            if ("".equals(sex)) {
                sex = "M";
            }
            user.setSex(sex);
            user.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            user.setMobilePhone(cursor.getString(cursor
                    .getColumnIndex("mobilephone")));
            user.setAvatar(cursor.getString(cursor.getColumnIndex("avatar")));
            user.setSigNature(cursor.getString(cursor.getColumnIndex("sigNature")));
            user.setEmail(cursor.getString(cursor.getColumnIndex("email")));
            user.setDeptId(cursor.getInt(cursor.getColumnIndex("deptId")));
            user.setType(cursor.getInt(cursor.getColumnIndex("type")));
            if (cursor.getString(cursor.getColumnIndex("remark")) != null) {
                user.setReMark(cursor.getString(cursor.getColumnIndex("remark")));
            }
            if (cursor.getColumnIndex("isbother") != -1) {
                user.setIsBother(cursor.getInt(cursor.getColumnIndex("isbother")) == 1 ? true
                        : false);
            }
            if (cursor.getColumnIndex("istop") != -1) {
                user.setIsTop(cursor.getInt(cursor.getColumnIndex("istop")) == 1 ? true
                        : false);
            }

            String publicKey = cursor.getString(cursor.getColumnIndex("publicKey"));
            if (publicKey == null || "".equals(publicKey)) {
                user.setPublicKey(null);
            } else {
                user.setPublicKey(publicKey);
            }
            String walletAddress = cursor.getString(cursor.getColumnIndex("walletAddress"));
            if (walletAddress == null || "".equals(walletAddress)) {
                user.setWalletAddress(null);
            } else {
                if (!walletAddress.toLowerCase().startsWith("0x")) {
                    walletAddress = "0x" + walletAddress;
                }
                user.setWalletAddress(walletAddress);
            }
            String rsaPublicKey = cursor.getString(cursor.getColumnIndex("RSAPublicKey"));
            if (rsaPublicKey == null || "".equals(rsaPublicKey)) {
                user.setRSAPublicKey(null);
            } else {
                user.setRSAPublicKey(rsaPublicKey);
            }
            String wechatQrUrl = cursor.getString(cursor.getColumnIndex("wechatQrUrl"));
            String zhifubaoQrUrl = cursor.getString(cursor.getColumnIndex("zhifubaoQrUrl"));
            user.setWeixinQrUrl((wechatQrUrl == null || "".equals(wechatQrUrl)) ? null : wechatQrUrl);
            user.setZhifubaoQrUrl((zhifubaoQrUrl == null || "".equals(zhifubaoQrUrl)) ? null : zhifubaoQrUrl);
            user.setAllowStrangerChat(cursor.getInt(cursor.getColumnIndex("stranger_chat")) == 1);
            user.setPlanet(cursor.getColumnIndex("planet") == -1 ? "" :
                    cursor.getString(cursor.getColumnIndex("planet")));

            list.add(user);
        }

        cursor.close();
        return list;
    }

    private ContentValues getUserContentValues(User user) {
        ContentValues values = new ContentValues();
        values.put("userId", user.getId());

        values.put("name", user.getName());
        values.put("nickName", user.getNickName());
        values.put("nickname_py_initial", ChineseCharacterUtils.getJianPin(user.getNickName()));
        values.put("nickname_py_quanpin", ChineseCharacterUtils.getQuanPin(user.getNickName()));
        values.put("sex", user.getSex());
        values.put("phone", user.getPhone());
        values.put("mobilephone", user.getMobilePhone());
        values.put("avatar", user.getAvatar());
        values.put("email", user.getEmail());
        values.put("sigNature", user.getSigNature());
        values.put("type", user.getType());
        values.put("deptId", Integer.valueOf(user.getDeptId()));
        values.put("enable", 1);

        //eth钱包字段
        values.put("walletAddress", user.getWalletAddress() == null ? "" : user.getWalletAddress());
        values.put("publicKey", user.getWalletAddress() == null ? "" : user.getPublicKey());
        values.put("RSAPublicKey", user.getWalletAddress() == null ? "" : user.getRSAPublicKey());

        //付款码
        values.put("wechatQrUrl", user.getWeixinQrUrl() == null ? "" : user.getWeixinQrUrl());
        values.put("zhifubaoQrUrl", user.getZhifubaoQrUrl() == null ? "" : user.getZhifubaoQrUrl());
        //允许陌生人发送消息
        values.put("stranger_chat", user.isAllowStrangerChat() ? 1 : 0);
        //星球
        values.put("planet", user.getPlanet() == null ? "" : user.getPlanet());
        return values;
    }


    /**
     * 关闭数据库
     */
    public void close() {
        this.db.close();
    }
}
